package com.sudo.boot.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class NettyServer {
    public static void main(String[] args) {
        // 创建 一个只处理连接请求的线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup(10);
        // 创建一个只处理客户端读写业务的线程组
        EventLoopGroup workerGroup = new NioEventLoopGroup(10);
        // 创建一个启动对象
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                // 使用NioServerSocketChannel作为服务器的通道实现
                .channel(NioServerSocketChannel.class)
                // 配置用于存放因没有空闲线程导致连接请求被暂存到队列中，队列长度
                .option(ChannelOption.SO_BACKLOG, 1024)
                // 创建通道初始化的对象并配置该对象，想改对象中添加处理器来实现具体的业务
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        // 添加处理器，处理器里面是真正处理业务的
                        socketChannel.pipeline().addLast(new NettyServerHandler());
                    }
                });
        System.out.println("Netty服务端启动了");
        try {
            // 阻塞启动
            ChannelFuture channelFuture = bootstrap.bind(8888).sync();
            // 阻塞关闭
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }
}
